import '../../form/form_validator.dart';
import 'form_input.dart';
import 'package:flutter/material.dart';

import '../../../utils/date_utils_ext.dart' show stringToDate;

///带输入框的日期选择器
class DateInput extends StatefulWidget {
  const DateInput(
      {super.key,
      this.initialValue,
      this.hintText,
      this.width,
      this.labelText,
      this.onChanged,
      this.autovalidateMode = AutovalidateMode.always,
      this.lastDate});
  final String? initialValue;
  final String? hintText;
  final double? width;
  final String? labelText;
  final ValueChanged<String>? onChanged;
  final DateTime? lastDate;
  final AutovalidateMode autovalidateMode;
  @override
  State<StatefulWidget> createState() => _DateInputState();
}

class _DateInputState extends State<DateInput> {
  TextEditingController? _controller;

  @override
  void dispose() {
    if (_controller != null) {
      _controller!.dispose();
      _controller = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _controller ??= TextEditingController(text: widget.initialValue);
    return FormInput(
      controller: _controller,
      hintText: widget.hintText,
      labelText: widget.labelText,
      width: widget.width,
      onChanged: widget.onChanged,
      maxLines: 1,
      autovalidateMode: widget.autovalidateMode,
      validator: (value) => validateDate(value, null),
      suffix: InkWell(
        onTap: () async {
          DateTime initialDate = DateTime.now();
          if (_controller!.text.isNotEmpty) {
            initialDate = stringToDate(_controller!.text) ?? DateTime.now();
          }
          DateTime? selectedDateTime = await showDatePicker(
              context: context,
              initialDate: initialDate,
              firstDate: DateTime(1900),
              lastDate: widget.lastDate ?? DateTime(DateTime.now().year + 100));
          if (selectedDateTime != null) {
            String text = selectedDateTime.toString().split(" ")[0];
            setState(() {
              _controller!.value = TextEditingValue(text: text);
            });
            if (widget.onChanged != null) {
              widget.onChanged!(text);
            }
          }
        },
        child: const Icon(
          Icons.calendar_month,
          size: 16,
        ),
      ),
    );
  }
}
